package com.zl.bootsecurityjwt.service;

import com.zl.bootsecurityjwt.common.jwt.JwtTokenTemplate;
import com.zl.bootsecurityjwt.mapper.UserMapper;
import com.zl.bootsecurityjwt.model.JwtParam;
import com.zl.bootsecurityjwt.model.LoginUser;
import com.zl.bootsecurityjwt.model.Permissions;
import com.zl.bootsecurityjwt.model.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

@Service
public class JwtUserDetailsService implements UserDetailsService {

    @Autowired
    private JwtTokenTemplate iwtTokenTemplate;

    @Autowired
    private UserMapper userMapper;

    /**
     * 登录认证
     * @param userName
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        JwtParam userInfo=userMapper.getUserInfo(userName);
        if (userInfo == null) {
            return null;
        }else {
            return new User(userInfo.getUsername(), userInfo.getPassword(),
                    new ArrayList<>());
        }
    }

    /**
     * 获取角色和权限
     * @return
     */
    public LoginUser getUserList() {
        LoginUser lg= new LoginUser();
        Set<String> role = new HashSet<>();
        Set<String> permissions = new HashSet<>();
        Set<Role> roleList = userMapper.getRole(iwtTokenTemplate.getUserName());
        roleList.stream().forEach(a->{
            role.add(a.getName());
        });
        lg.setRoles(role);
        userMapper.getPermissions(roleList).stream().forEach(b->{
            permissions.add(b.getCode());
        });
        lg.setUsername(iwtTokenTemplate.getUserName());
        lg.setPermissions(permissions);
        return lg;
    }
}